import { ref } from 'vue'
import app from '@/app'
import checkout from './checkout'
import { user, logout, login } from '@/api/manage/account'

import base from '@/app/model'

// 继承总模型
const model = new base;

// 收银台信息
model.checkout = ref({})

// 获取收银台
model.getCheckout = () => {
  return model.checkout.value
}

// 获取店长用户信息
model.getUser = () => {
  return model.getData().user
}

model.get = () => {
  return new Promise((resolve, jeject) => {
    user().then(res => {
      model.setData(res)
      // 我的收银台
      model.checkout.value = res.checkout
      // 加载收银台
      checkout.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      app.ui.loadingClose()
    })
  })
}

model.login = (data) => {
  return new Promise((resolve, jeject) => {
    app.ui.loading()
    login(data).then(res => {
      // 存储Token
      app.token(res.token)
      // 存入帐号
      app.account(data.username)
      // 获取信息
      model.get().then(() => {
        // 进入 Account 客户端
        app.route.to('/account')
      })
      resolve(res)
    }).catch(res => {
      app.ui.message('error', res.message)
      jeject(res)
    }).finally(() => {
      app.ui.loadingClose()
    })
  })
}

model.logout = () => {
  return new Promise((resolve, jeject) => {
    logout().then(res => {
      model.setData({})
      model.checkout.value = {}
      // 清除token
      app.logout()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

export default model